package com.niuke;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * @ClassName : NC37
 * @Author : kele
 * @Date: 2023/4/2 13:43
 * @Description :
 */
class Interval {
    int start;
    int end;

    Interval() {
        start = 0;
        end = 0;
    }

    Interval(int s, int e) {
        start = s;
        end = e;
    }
}

public class NC37 {

    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {

        if (intervals.size() <= 1) {
            return intervals;
        }

        intervals.sort(Comparator.comparingInt(o -> o.start));
        ArrayList<Interval> result = new ArrayList<>();

        for (Interval interval : intervals) {
            if (result.isEmpty()) {
                result.add(interval);
            }

            Interval bef = result.get(result.size() - 1);

            if (bef.end >= interval.start) {
                bef.end = Math.max(bef.end,interval.end);
            } else {
                result.add(interval);
            }

        }
        return result;
    }

}
